# -*- coding: UTF-8 -*-

#Honteusement pompé ici : http://larrymyers.com/articles/3/creating-a-jinja-pygments-extension-for-code-highlighting
import datetime
from jinja2 import nodes
from jinja2.ext import Extension

from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer, get_lexer_by_name

"""
TODO: Ajouter d’autres filters pour coller au plus près de Jekyll
"""

class PygmentsExtension(Extension):
    """
    A Pygments extension for use with the Jinja2 template language.
    
    Setup:
    
    import PygmentsExtension
    from jinja2 import Environment
    
    jinja2_env = Environment(extensions=[PygmentsExtension])
    
    Usage:
    
    {% highlight 'javascript' %}
    function foo() { console.log('bar'); }
    {% endhighlight %}
    """
    tags = set(['highlight'])
    
    def __init__(self, environment):
        super(PygmentsExtension, self).__init__(environment)
        
        # add the defaults to the environment
        environment.extend(pygments=self)
    
    def parse(self, parser):
        lineno = parser.stream.next().lineno
        
        args = []
        lang_type = parser.parse_expression()
        
        if lang_type is not None:
            args.append(lang_type)
        
        body = parser.parse_statements(['name:endhighlight'], drop_needle=True)
        
        return nodes.CallBlock(self.call_method('_pygmentize', args), 
                                [], [], body).set_lineno(lineno)
    
    def _pygmentize(self, lang_type, caller):
        lexer = None
        formatter = HtmlFormatter(linenos='table')
        content = caller()
        
        if lang_type is None:
            lexer = guess_lexer(content)
        else:
            lexer = get_lexer_by_name(lang_type)
        
        return highlight(content, lexer, formatter)
    


def date_to_xmlschema(value):
    """
    Convert a datetime value to be used as a string like "2012-02-24T20:56:27.077423+01:00"
    """
    #TODO: Enhence this, use raise error…
    if(len(value) == 4+1+2+1+2):
        d = datetime.datetime.strptime(value, '%Y-%m-%d')
    else:
        d = datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')

    dtnow = datetime.datetime.now()
    dtutcnow = datetime.datetime.utcnow()
    delta = dtnow - dtutcnow
    hh, mm = divmod((delta.days * 24 * 60 * 60 + delta.seconds + 30) // 60, 60)
    #return "%s+%02d:%02d" % (dtnow.isoformat(), hh, mm)
    return "%s+%02d:%02d" % (d.isoformat(), hh, mm)

